package com.leon.registerserver;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class HeartbeatMessuredRate {

    /**
     * 单例实例
     */
    private static HeartbeatMessuredRate instance =
            new HeartbeatMessuredRate();

    private HeartbeatMessuredRate() {
        Daemon daemon = new Daemon();
        daemon.setDaemon(true);
        daemon.start();
    }

    /**
     * 最近一分钟的心跳次数
     */
    private LongAdder latestMinuteHeartbeatRate;
    /**
     * 最近一分钟的时间戳
     */
    private long latestMinuteTimestamp = System.currentTimeMillis();

    /**
     * 获取单例实例
     *
     * @return
     */
    public static HeartbeatMessuredRate getInstance() {
        return instance;
    }

    /**
     * 增加一次最近一分钟的心跳次数
     */
    public void increment() {
        long currentTime = System.currentTimeMillis();

        if (currentTime - latestMinuteTimestamp > 60 * 1000) {
            latestMinuteHeartbeatRate = new LongAdder();
            this.latestMinuteTimestamp = System.currentTimeMillis();
        }

        latestMinuteHeartbeatRate.increment();
    }

    /**
     * 获取最近一分钟的心跳次数
     */
    public long get() {
        return latestMinuteHeartbeatRate.longValue();
    }

    private class Daemon extends Thread {

        @Override
        public void run() {
            while (true) {
                try {
                    synchronized (HeartbeatMessuredRate.class) {
                        long currentTime = System.currentTimeMillis();
                        if (currentTime - latestMinuteTimestamp > 60 * 1000) {
                            latestMinuteHeartbeatRate = new LongAdder();
                            latestMinuteTimestamp = System.currentTimeMillis();
                        }
                    }
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
